package jsf;

import java.io.Serializable;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import data.GenderEnum;
import util.SessionUtil;
import ejb.StudentsBeanRemote;
import entity.Students;

@RequestScoped
@ManagedBean
public class StudentsController implements Serializable {

	private static final long serialVersionUID = 1L;
	@EJB(lookup="java:global/EnrollmentManagementEAP/EnrollmentManagementEJB/StudentsBean!ejb.StudentsBeanRemote")
	StudentsBeanRemote bean;
	private Long selectedId;
	private ArrayList<Students> students = new ArrayList<Students>();
	private Students student = new Students();
	private ArrayList<GenderEnum> genders = new ArrayList<GenderEnum>();
	
	public StudentsController() {
		SessionUtil.authenticate();
	}
	
	public ArrayList<Students> getStudents() {
		ArrayList<Students> students = new ArrayList<Students>();
		students.addAll(bean.getAll());
		this.students = students;
		return this.students;
	}
	
	public ArrayList<GenderEnum> getGenderEnum() {
		ArrayList<GenderEnum> genders = new ArrayList<GenderEnum>();
		genders.add(GenderEnum.MALE);
		genders.add(GenderEnum.FEMALE);
		this.genders = genders;
		return this.genders;
	}
	
	public Students getStudent() {
		return this.student;
	}

	private Long getSelectedId() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        return Long.parseLong(context.getRequestParameterMap().get("selectedId"));
    }
	
	public String edit() {
        selectedId = this.getSelectedId();
        if(selectedId != null) {
            this.student = this.bean.get(selectedId);
            return "student.xhtml";
        }
        return "students.xhtml";
    }
	
	// For Index Form
	public String create() {
		this.selectedId = null;
        this.student = new Students();
        return "student.xhtml";
    }
	
	// For Edit Form
	public String doSubmit() {
        if(selectedId == null) {
            return this.doCreate();
        } else {
            return this.doEdit();
        }
    }
	
	// For Edit Form
	public String doEdit() {
        this.bean.update(this.student);
        return "students.xhtml";
    }
    
	// For Edit Form
    public String doCreate() {
    	this.bean.insert(this.student);
        return "students.xhtml";
    }
	
    // For Index Form
	public void doDelete() {
        Long selectedId = this.getSelectedId();
        Students selectedStudent = this.bean.get(selectedId);
        if(selectedStudent != null) {
            this.bean.delete(selectedStudent);
        }
    }
}
